var flag = false;
var InvestorModule = function () {
	

	$('#btn_reset').click(function(){
		$('#empGroupTree').jstree().refresh(true,true);
		$('#urls').val('');
	});
	
	var handleResourceTree = function() {
		$('#empGroupTree').jstree({
			'plugins' : [ "wholerow", "checkbox", "types" ],
			'core' : {
				"themes" : {
					"responsive" : false
				},
				'data' : {
					"url" : ctx + "/investor/empTree",
					"data" : function(node) {

					}
				}
			},
			"types" : {
				"default" : {
					"icon" : "fa fa-folder icon-warning icon-lg"
				},
				"file" : {
					"icon" : "fa fa-file icon-warning icon-lg"
				}
			}
		}).on("changed.jstree", function(e, data) {
			$('#urls').val(data.selected);
			var json = "{\"groupId\":\""+data.selected+"\"}"; 
			$.ajax({
            	contentType:"application/json; charset=UTF-8",
                dataType : 'json',
                type : "POST",
                url : ctx + "/appointment/queryEmpGroup",
                data : json,
                success: function(msg){
                	var data = msg.data;
                	if(data == null||data.length == 0){
                		$('#dept').val("");
                		return;
                	}
                	var str = "";
                	for(var i=0;i<data.length;i++){
                		str += data[i]+"  ";
            		}
                	$('#dept').val(str);
                },
                error: function (msg) {
                	$('#dept').val("");
                }
            });
		});
	};
    var editable = function () {
        return {
            init: function () {
                var oTable = $('#modelEditable').dataTable({
                    "lengthMenu": [
                        [10, 15, 20, 50],
                        [10, 15, 20, 50]
                    ],
                    "autoWidth":false,
                    "displayLength": 10,
                    "scrollX": true,
                    "language": {
                        "lengthMenu": "每页 _MENU_ 条记录",
                        "paginate": {
                            "previous": "上一页",
                            "next": "下一页"
                        },
                        "info" : "从 _START_ 到  _END_ 条，总记录为 _TOTAL_ 条",    
                        "infoEmpty" : "记录数为0",
                    },
                    "columnDefs": [
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [0]
						},
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [1]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [2]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [3]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [4]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "<center>-</center>",
						    "targets": [5]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "-",
						    "targets": [6]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "-",
						    "targets": [7]
						}, 
						{
						    "data": null,
						    'sortable': false,
						    "defaultContent": "-",
						    "targets": [8]
						}
                    ],
                    "columns": [
                       { "data": "name" },
                       { "data": "gender" },
                       { "data": "idCard" },
                       { "data": "mobile" },
                       { "data": "groupName" },
                       { "data": "employeeName" },
                       { "data": "registerTime" },
                       { "data": "invitationCode" }
                   ],
                   "filter" : false,
                   "processing": false,
                   "serverSide": true,
                   "ajaxSource": ctx + "/investor/query",
                   "serverMethod": "post",
                   "fnRowCallback" : function(nRow, aData, displayIndex) {
                	   nRow.children[0].id = aData.id;
                	   var gender = aData.gender;//registerTime
                	   if (gender == '1') {
                		   $('td:eq(1)', nRow).html('男');
                	   }else if(gender == '2'){
                		   $('td:eq(1)', nRow).html('女');
                	   }else{
                		   $('td:eq(1)', nRow).html('-');
                	   }
                	   var registerTime = aData.registerTime
                	   if(registerTime == null){
                		   $('td:eq(6)', nRow).html('-'); 
                	   }else{
                		   registerTime = registerTime.substr(0, 10)
                		   $('td:eq(6)', nRow).html(registerTime); 
                	   }
                	   //s.substr(12, 5)
                	   var code = aData.invitationCode;
                	   if(code == null){
                		   $('td:eq(7)', nRow).html('-'); 
                	   }else{
                		   $('td:eq(7)', nRow).html(code); 
                	   }
                	   var contact
                	   if (aData.employeeName == null) {
                		   aData.employeeName = '-';
                	   }
                	   if (aData.employeeNo == null) {
                		   aData.employeeNo = '-';
                		   contact = "<center>-</center>";
                	   }else{
                		   contact = "<center>" + aData.employeeName + "<br>(工号:" + aData.employeeNo + ")</center>";
                	   }
                	   var idcard
                	   if(aData.idCard == null){
                		   idcard = '<center>-</center>';
                	   }else{
                		   if(aData.idType == undefined){
                			   idcard = "<center>" + aData.idCard + "<br></center>";   
                		   }else{
                			   idcard = "<center>" + aData.idCard + "<br>"+ aData.idType + "</center>"; 
                		   }
                	   }
                	   $('td:eq(2)', nRow).html(idcard);
                	   $('td:eq(5)', nRow).html(contact);
                	   $('td:eq(8)', nRow).html('<a class="detail fa fa-bars fa-lg " title="详情" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;<a class="relation fa fa-comments fa-lg " title="联系记录" href="javascript:;"></a>&nbsp;&nbsp;&nbsp;<a class="sendInvitationCode fa fa-paper-plane-o fa-lg " title="发送邀请码" href="javascript:;"></a>');
                       return nRow;
                   },
                   "fnServerData" : function(ajaxSource, dataSet, fnCallback) {
	                   var json = "";
	                   var s;
	                   for (var i = 0; i < dataSet.length; i++) {
	                       s = dataSet[i];
	                   	   if (s.name == 'sEcho') {
	                   		   json = json + '"echo":' + s.value;
		                   } else if (s.name == 'iDisplayStart') {
		                	   json = json + ',"page":' + s.value;
		                   } else if (s.name == 'iDisplayLength') {
		                	   json = json + ',"pageSize":' + s.value;
		                   }
	                   }
	                   //解析当前href参数字段
            	       var result = {};
            	       var params = (window.location.search.split('?')[1] || '').split('&');
            	       for(var param in params) {
            	    	   if (params.hasOwnProperty(param)) {
	            	            paramParts = params[param].split('=');
	            	            result[paramParts[0]] = decodeURIComponent(paramParts[1] || "");
            	    	   }
            	       }
            	       var form = $("form#queryForm").serializeJSON();
                   	   var js = form.replace('}', ',');
                   	   json = js + json + "}";
                   	   var obj = jQuery.parseJSON(json);
                   	   var groupId = result.groupId;
            	       if( groupId != undefined && flag == false){
            	    	    flag = true;
            	    	    obj.groupId = groupId;
            	    	    var se1 = $('#groupId')[0];
            	    		var i=0;
            	    		var lenth = se1.length;
            	    	    for(;i<lenth;i++) {
            	    	    	if(se1[i].value == groupId){
            	    	    		se1[i].selected = true;
            	    	    	}
            	    	    }
            	       }
            	       json = JSON.stringify(obj);
                       $.ajax({
                       	   "contentType":"application/json; charset=UTF-8",
                           "dataType" : 'json',
                           "type" : "POST",
                           "url" : ctx + "/investor/query",
                           "data" : json,
                           "success" : fnCallback
                       });
                   },
                });
                // 联系记录
                $('#modelEditable').on("click", "a.relation", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    window.location.href = ctx +"/investor/relation/"+id;
                    return;
                }));
                // 明细
                $('#modelEditable').on("click", "a.detail", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    window.location.href = ctx +"/investor/detail/"+id;
                    return;
                }));
                //发送邀请码
                $('#modelEditable').on("click", "a.sendInvitationCode", (function (e) {
                    e.preventDefault();
                    var nRow = $(this).parents('tr')[0];
                    var id = nRow.children[0].id;
                    $.ajax({
                    	type:"post",
                        url: ctx + "/investor/sendInvitationCode/" + id,
                        success: function(msg){
                        	if(msg.code == 1){
                        		bootbox.alert("发送邀请码成功！");
                        	}else{
                        		bootbox.alert(msg.message);
                        	}
                        },
                        error: function (msg) {
                        	bootbox.alert("服务器偷了个小懒,新增投资人失败了！");
                        }
                    });
                }));
                $('#btn_query').click(function(){
                	oTable.fnClearTable();
                });
            }

        };
    }();
    return {
        init: function () {
        	editable.init();
        	handleResourceTree();
        }
    };
}();
